<template>
  <div>
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['质量管理']" currentMenu="不合格品待处理"></crumbs>
    <a-card :bordered="false" style="height:100%;margin-top:12px">
      <a-button @click="handleShowFilter" icon="filter">筛选 <span class="filter-num" style="margin-left:5px">{{ ' '+ filteredNums }}</span></a-button>
      <a-button @click="showColumn" icon="unordered-list" class="btns">设置列</a-button>
      <div class="right-btn">
        <!-- <a-button @click="exportFile" class="btns">导出</a-button> -->
      </div>
      <a-table :key="tableKey" row-key="id" size="middle" :scroll="{ x: scrollX, y: 'calc(100vh - 366px)' }" :hideDefaultSelections="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle:' ',columnWidth:35, onChange: onSelectChange}" :columns="columns" :dataSource="modelList" :pagination="false" @change="tableChange"
        style="margin-top:24px" :components="drag(columns, 'DEFECTS_PENDING_LIST')">
        <span slot="actions" slot-scope="text, record">
          <a @click="handleEdit(record)" v-if="record.handleStatus == 'finish'">查看明细</a>
          <a @click="handle(record)" v-else>处理</a>
        </span>
        <!-- 行信息 -->
        <span slot="orderCode" :title="record.orderCode" slot-scope="text, record" class="btn-text" @click="orderDetail(record)">
          {{ record.orderCode }}
        </span>
        <div slot="batchCode" slot-scope="text, record" class="btn-text ant-table-row-cell-ellipsis" :title="text" @click="batchRecord(record)">{{text|| '-'}}</div>
        <span slot="goodsName" :title="record.goodsName" slot-scope="text, record">
          {{  record.goodsName  }}
        </span>
        <span slot="notQualityNum" :title="record.notQualityNum" slot-scope="text, record">
          {{ numFormat(record.notQualityNum) }}
        </span>
        <span slot="alreadyHandleNum" :title="record.alreadyHandleNum" slot-scope="text, record">
          {{ numFormat(record.alreadyHandleNum) }}
        </span>
        <span slot="handleStatus" slot-scope="text, record" :class="record.handleStatus?record.handleStatus:''">
          {{ record.handleStatus == 'notStart' ? '未开始' : record.handleStatus == 'handling' ? '正在处理' : record.handleStatus == 'finish' ? '处理完成' : '-' }}
        </span>
        <!-- 输入框搜索 -->
        <div slot="searchInput" slot-scope="{ selectedKeys, confirm, clearFilters, column }" class='searchWorkOreder'>
          <a-input placeholder='请输入' v-model="filterForm[column.dataIndex]" style="width: 188px;display: block;" @pressEnter="handleSearch" />
          <a-button type="primary" style="width: 80px; margin-left: 20px;display: block;" @click="() => handleSearch(selectedKeys, confirm, column.dataIndex,clearFilters)">
            搜索
          </a-button>
        </div>
        <a-icon slot="searchIcon" slot-scope="filtered" type="search" :style="{ color: filtered ? '#108ee9' : undefined }" />
        <!-- 选择搜索 -->
        <div slot="selectDropdown" slot-scope="{confirm, clearFilters, column}" class='searchWorkOreder'>
          <a-select mode="multiple" allowClear placeholder="请选择" style="width: 200px" v-model="filterForm[column.dataIndex]" @change="(v) => changeStatus(v, column.dataIndex)">
            <a-select-option value="notStart">未开始</a-select-option>
            <a-select-option value="handling">正在处理</a-select-option>
            <a-select-option value="finish">处理完成</a-select-option>
          </a-select>
          <a-button type="primary" style="width: 80px; margin-left: 20px;display: block;" @click="() => handleSearch(confirm, column.dataIndex,clearFilters)">
            搜索
          </a-button>
        </div>
        <a-icon slot="selectIcon" slot-scope="filtered" type="filter" :style="{ color: filtered ? '#108ee9' : undefined }" />
        <!-- 人员选择 -->
        <div slot="selectPeople" slot-scope="{confirm, clearFilters, column }" class='searchWorkOreder'>
          <j-select-user-by-dep @changeRow="userFilter" v-model="userIds" :limit="5" :seldep='true' :modalWidth="1000" :multi="true"></j-select-user-by-dep>
          <a-button type="primary" style="width: 80px; margin-left: 20px;display: block;" @click="() => handleSearch(confirm, column.dataIndex,clearFilters)">
            搜索
          </a-button>
        </div>
        <a-icon slot="peopleIcon" slot-scope="filtered" type="filter" :style="{ color: filtered ? '#108ee9' : undefined }" />
        <!-- 日期搜索 -->
        <div slot="datePicker" slot-scope="{confirm, clearFilters, column}" class='searchWorkOreder'>
          <a-range-picker style="width:188px" format="YYYY-MM-DD" v-model="dateForm[column.dataIndex]" :placeholder="['开始时间', '结束时间']" @change="onOk" />
          <a-button type="primary" style="width: 80px; margin-left: 20px;display: block;" @click="() => handleSearch(confirm, column.dataIndex,clearFilters)">
            搜索
          </a-button>
        </div>
        <a-icon slot="dateIcon" slot-scope="filtered" type="filter" :style="{ color: filtered ? '#108ee9' : undefined }" />
      </a-table>
      <SetColumn columnName="设置列" ref="SetColumn" v-if="showSetColumn" @sureBtn="sureBtn" @cancelBtn="showSetColumn = false" />
    </a-card>
    <a-drawer placement="right" width="500" :visible="showFilter" @close="closeFilter">
      <div class="filter-body">
        <div slot="title" class="uni-card filter-tit">筛选 <span class="filter-num">{{ filteredNums }}</span></div>
        <div class="uni-card" v-if="filteredNums > 0" style="background:#fff">
          <div v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
            <span class="filter-tag" @click="delFiltered(item.key)">
              <span class="tag-text" :title="`${item.title}：${item.text}`">{{ `${item.title}：${item.text}` }}</span>
              <a-icon type="close" />
            </span>
          </div>
        </div>
        <div style="overflow-y:scroll;flex:1;padding:0">
          <div class="uni-card" style="background:#fff">
            <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
              <a-form-model-item label="处理状态">
                <a-select mode="multiple" allowClear placeholder="请选择" style="width: 100%" v-model="filterForm.handleStatus" @change="(v) => changeStatus(v, 'handleStatus')">
                  <a-select-option value="notStart">未开始</a-select-option>
                  <a-select-option value="handling">正在处理</a-select-option>
                  <a-select-option value="finish">处理完成</a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="工单编号">
                <a-input v-model="filterForm.orderCode" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="批次编号">
                <a-input v-model="filterForm.batchCode" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="产品名称">
                <a-input v-model="filterForm.goodsName" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="规格">
                <a-input v-model="filterForm.spec" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="工序名称">
                <a-input v-model="filterForm.processName" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="操作人">
                <!-- <a-input v-model="filterForm.operateId" placeholder="请输入" /> -->
                <j-select-user-by-dep :limit="5" @changeRow="userFilter" v-model="userIds" :seldep='true' :modalWidth="1000" :multi="true"></j-select-user-by-dep>
              </a-form-model-item>
              <a-form-model-item label="提交时间">
                <a-range-picker style="width:100%" format="YYYY-MM-DD" v-model="dateForm.applyTime" :placeholder="['开始时间', '结束时间']" @change="onOk" />
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
        <div class="footer-submit">
          <a-button class="margin-btn" @click="resetFilter">重置</a-button>
          <a-button type="primary" @click="handleFilter">确定</a-button>
        </div>
      </div>
    </a-drawer>
    <a-modal title="不合格品处理" :width="1200" :visible="handleVisible" :confirm-loading="confirmHandleLoading" @ok="handleOk" @cancel="handleCancel">
      <a-table :key="modalKey" row-key="id" size="middle" :scroll="{ x: 1120, y: 300 }" :hideDefaultSelections="false"
        :row-selection="{ selectedRowKeys: handelTable.handleSelectedRowKeys, columnTitle:' ', onChange: handleSelectChange, fixed: true}" :columns="handleColumns" :dataSource="handelTable.handlePageList"
        :pagination="false" :loading="handelTable.loading" class="j-table-force-nowrap">
        <span slot="orderCode" slot-scope="text, record" class="btn-text" @click="orderDetail(record)">
          {{ record.orderCode }}
        </span>
        <span slot="handleType" slot-scope="text, record">
          <a-select placeholder="请选择" allowClear style="width: 100px" v-model="record.handleType">
            <a-select-option value="repair">返修</a-select-option>
            <a-select-option value="compromise">让步接收</a-select-option>
            <a-select-option value="scrap">报废</a-select-option>
          </a-select>
        </span>
        <span slot="failedProcessId" slot-scope="text, record, index">
          <a-select :key="failedProcessIndex" placeholder="请选择" allowClear style="width: 100px" v-model="record.failedProcessId" @focus="getFailedList(record, index)" @change="e => changeProcess(e, index, record)">
            <a-select-option v-for="ops in failedList[index] ? failedList[index].list : []" :key="ops.failedProcessId" :title="ops.failedProcessName">{{ ops.failedProcessName }}</a-select-option>
          </a-select>
        </span>
        <span slot="failedOperatorId" slot-scope="text, record, index">
          <a-select mode="multiple" :key="failedOperatorIndex" placeholder="请选择" allowClear style="width: 100%" v-model="record.failedOperatorId" @change="changeOperator">
            <a-select-option v-for="ops in failedOperatorList[index] ? failedOperatorList[index].list : []" :key="ops.failedOperatorId" :title="ops.failedOperatorName">{{ ops.failedOperatorName }}</a-select-option>
          </a-select>
        </span>
        <span slot="notQualityNum" slot-scope="text, record">
          {{ numFormat(record.canHandleNum) }}
        </span>
        <span slot="notQualityNum" slot-scope="text, record">
          {{ numFormat(record.notQualityNum) }}
        </span>
        <span slot="alreadyHandleNum" slot-scope="text, record">
          {{ numFormat(record.alreadyHandleNum) }}
        </span>
        <span slot="num" slot-scope="text, record, index">
          <a-input v-model="record.num" @input="(e) => inputNum(e, index)" @blur="(e) => blurNum(e, index)" style="width: 100px" placeholder="请输入" />
        </span>
        <span slot="actions" slot-scope="text, record, index">
          <a @click="handleDelete(index)">删除</a>
        </span>
      </a-table>
      <!-- 全选/分页 -->
      <div style="padding-top:24px">
        <div style="display: inline-block;padding-left:22px">
          <a-checkbox :indeterminate="handelTable.listIndeterminate" :checked="handelTable.listCheckAll" @change="handleCheckAllChange"></a-checkbox>
          <span class='btn-text' style="margin:0 24px" @click="deleteAll">删除</span>
          <span style="margin-left: 8px">
            {{ `已选 ${handelTable.handleSelectedRowKeys.length}/${handelTable.handleList.length} 项` }}
          </span>
        </div>
        <div style="display: inline-block; float: right">
          <a-pagination :total="handelTable.handleList.length" v-model="handelTable.current" :page-size-options="handelTable.pageSizeOptions" :page-size="handelTable.pageSize"
            @change="handleChangePage" @showSizeChange="handleShowSizeChange" show-quick-jumper show-size-changer />
        </div>
      </div>
    </a-modal>
    <!-- 全选/分页 -->
    <div class="uni-card" :style="{position: 'fixed', bottom:0,right:0,left:collapsed?'79px':'208px', background: '#fff',paddingLeft:'50px'} ">
      <div style="display: inline-block">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <!-- <span class='btn-text' style="margin:0 24px" @click="batchAction">批量处理</span> -->
        <a-button type="link" @click="batchAction" :loading="loadingBatch">
          批量处理
        </a-button>
        <span style="margin-left: 8px">
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }} <span class='btn-text' @click="clearArr" style="margin: 0 10px">清空</span>
        </span>
      </div>
      <div style="display: inline-block; float: right">
        <a-pagination :total="total" v-model="current" :page-size-options="pageSizeOptions" :page-size="pageSize" @change="onChangePage" @showSizeChange="onShowSizeChange" show-quick-jumper
          show-size-changer />
      </div>
    </div>
    <batch-production ref="BatchProduction"></batch-production>
    <windowDetail ref="windowDetail"></windowDetail>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import crumbs from '@/components/crumbs.vue'
import { getNewColumns, subStrText, clearNoNum, camelCase2UnderLine, numFormat } from '@/utils/util'
import { API } from '@/api/requestFzs'
import moment from 'dayjs'
import { mapState } from 'vuex'
import tableDragResize from '@/mixins/tableDragResize'
import BatchProduction from '@/pubComponent/BatchProduction'
import windowDetail from '@/views/workManagement/workOrder/workOrderDetail'
// 表头
const columnsValue = [
  {
    title: '工单编号',
    fixed: 'left',
    dataIndex: 'orderCode',
    ellipsis: true,
    sorter: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'orderCode',
    },
  },
  {
    title: '批次编号',
    dataIndex: 'batchCode',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'batchCode',
    },
  },
  {
    title: '产品编号',
    
    dataIndex: 'goodsCode',
    ellipsis: true,
    width: 150,
  },
  {
    title: '产品名称',
    
    dataIndex: 'goodsName',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'goodsName',
    },
  },
  {
    title: '规格',
    
    dataIndex: 'spec',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'spec',
    },
  },
  {
    title: '基本单位',
    
    width: 150,
    dataIndex: 'basicUnitText',
    ellipsis: true,
  },
  {
    title: '工序编号',
    
    width: 150,
    dataIndex: 'processCode',
    ellipsis: true,
  },
  {
    title: '工序名称',
    
    dataIndex: 'processName',
    ellipsis: true,
    width: 150,
    scopedSlots: { customRender: 'processName' },
  },
  {
    title: '操作人',
    
    dataIndex: 'operatorIdText',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'selectPeople',
      filterIcon: 'peopleIcon',
      customRender: 'operatorIdText',
    },
  },
  {
    title: '报工单位',
    
    dataIndex: 'reportWorkUnitText',
    ellipsis: true,
    width: 150,
    scopedSlots: { customRender: 'reportWorkUnitText' },
  },
  {
    title: '不合格数量',
    
    dataIndex: 'notQualityNum',
    ellipsis: true,
    sorter: true,
    width: 150,
    scopedSlots: { customRender: 'notQualityNum' },
  },
  {
    title: '已处理数量',
    
    dataIndex: 'alreadyHandleNum',
    ellipsis: true,
    sorter: true,
    width: 150,
    scopedSlots: { customRender: 'alreadyHandleNum' },
  },
  {
    title: '处理状态',
    
    dataIndex: 'handleStatus',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'handleStatus',
    },
  },
  {
    title: '提交人',
    
    dataIndex: 'applicantIdText',
    ellipsis: true,
    width: 150,
    scopedSlots: { customRender: 'applicantIdText' },
  },
  {
    title: '提交时间',
    
    dataIndex: 'applyTime',
    ellipsis: true,
    sorter: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'datePicker',
      filterIcon: 'dateIcon',
      customRender: 'applyTime',
    },
  },
  // {
  //   fixed: 'right',
  //   title: '操作',
    
  //   dataIndex: 'actions',
  //   ellipsis: true,
  //   width: 150,
  //   scopedSlots: { customRender: 'actions' },
  // },
]
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    
    dataIndex: 'actions',
    width: 100,
    ellipsis: true,
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  mixins: [tableDragResize],
  data() {
    return {
      failedProcessIndex: 1.1,
      failedOperatorIndex: 1.2,
      numFormat,
      moment,
      subStrText,
      userIds: '',
      handleVisible: false,
      confirmHandleLoading: false,
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      showFilter: false, // 筛选抽屉
      modelList: [], // 列表数据
      selectedRowKeys: [], // 列表已选择数据
      showSetColumn: false, // 显示
      colunmArr: [
        {
          checkAll: false, //当前组是否全选
          indeterminate: false, //当前组不全选且有选择项时显示状态
          checkedList: [], //已选数据（不包括所有属性，只含有所选项的每一项的value）
          selectList: [], //已选数据（包括所有属性）
          topTitle: '基础字段', //当前组顶部字段
          plainOptions: [], //当前组提供可供选择的选项
        },
      ],
      //全选按钮
      indeterminate: false,
      checkAll: false,
      current: 1,
      total: 0,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      columns: [
        {
          title: '工单编号',
          fixed: 'left',
          dataIndex: 'orderCode',
          ellipsis: true,
          sorter: true,
          width: 150,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'orderCode',
          },
        },
        {
          title: '批次编号',
          dataIndex: 'batchCode',
          ellipsis: true,
          width: 150,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'batchCode',
          },
        },
        {
          title: '产品名称',
          
          dataIndex: 'goodsName',
          ellipsis: true,
          width: 150,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsName',
          },
        },
        {
          title: '工序名称',
          
          dataIndex: 'processName',
          // ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'processName' },
        },
        {
          title: '操作人',
          
          ellipsis: true,
          width: 150,
          dataIndex: 'operatorIdText',
          scopedSlots: {
            filterDropdown: 'selectPeople',
            filterIcon: 'peopleIcon',
            customRender: 'operatorIdText',
          },
        },
        {
          title: '报工单位',
          
          ellipsis: true,
          width: 150,
          dataIndex: 'reportWorkUnitText',
          scopedSlots: { customRender: 'reportWorkUnitText' },
        },
        {
          title: '不合格数量',
          
          dataIndex: 'notQualityNum',
          ellipsis: true,
          sorter: true,
          width: 150,
          scopedSlots: { customRender: 'notQualityNum' },
        },
        {
          title: '已处理数量',
          
          dataIndex: 'alreadyHandleNum',
          ellipsis: true,
          sorter: true,
          width: 150,
          scopedSlots: { customRender: 'alreadyHandleNum' },
        },
        {
          title: '处理状态',
          
          dataIndex: 'handleStatus',
          ellipsis: true,
          width: 150,
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'handleStatus',
          },
        },
        {
          title: '提交人',
          
          dataIndex: 'applicantIdText',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'applicantIdText' },
        },
        {
          title: '提交时间',
          
          dataIndex: 'applyTime',
          sorter: true,
          ellipsis: true,
          width: 150,
          scopedSlots: {
            filterDropdown: 'datePicker',
            filterIcon: 'dateIcon',
            customRender: 'applyTime',
          },
        },
        // {
        //   fixed: 'right',
        //   title: '操作',
          
        //   dataIndex: 'actions',
        //   ellipsis: true,
        //   width: 150,
        //   scopedSlots: { customRender: 'actions' },
        // },
      ],
      handleColumns: [
        {
          title: '工单编号',
          fixed: 'left',
          dataIndex: 'orderCode',
          ellipsis: true,
          sorter: true,
          width: 150,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'orderCode',
          },
        },
        {
          title: '批次编号',
          dataIndex: 'batchCode',
          ellipsis: true,
          width: 150,
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'batchCode',
          },
        },
        {
          title: '工序名称',
          
          dataIndex: 'processName',
          width: 180,
          ellipsis: true,
        },
        {
          title: '操作人',
          dataIndex: 'operatorIdText',
          ellipsis: true,
          width: 120,
        },
        {
          title: '报工单位',
          
          dataIndex: 'reportWorkUnitText',
          width: 120,
          ellipsis: true,
        },
        {
          title: '可处理数量',
          
          dataIndex: 'canHandleNum',
          width: 120,
          ellipsis: true,
          scopedSlots: { customRender: 'canHandleNum' },
        },
        {
          title: '已处理数量',
          
          dataIndex: 'alreadyHandleNum',
          width: 120,
          ellipsis: true,
          scopedSlots: { customRender: 'alreadyHandleNum' },
        },
        {
          title: '不合格数量',
          
          dataIndex: 'notQualityNum',
          width: 120,
          ellipsis: true,
          scopedSlots: { customRender: 'notQualityNum' },
        },
        {
          title: '产品名称',
          
          dataIndex: 'goodsName',
          width: 120,
          ellipsis: true,
        },
        {
          title: '规格',
          
          dataIndex: 'spec',
          width: 120,
          ellipsis: true,
        },
        {
          title: '基本单位',
          
          dataIndex: 'basicUnitText',
          width: 120,
          ellipsis: true,
        },
        {
          title: '提交人',
          
          dataIndex: 'applicantIdText',
          width: 120,
          ellipsis: true,
        },
        {
          title: '提交时间',
          
          dataIndex: 'applyTime',
          width: 190,
          ellipsis: true,
        },
        {
          fixed: 'right',
          title: '处理方式',
          
          dataIndex: 'handleType',
          width: 120,
          scopedSlots: { customRender: 'handleType' },
          ellipsis: true,
        },
        {
          fixed: 'right',
          title: '处理数量',
          
          dataIndex: 'num',
          width: 120,
          scopedSlots: { customRender: 'num' },
          ellipsis: true,
        },
        {
          fixed: 'right',
          title: '不合格工序',
          
          dataIndex: 'failedProcessId',
          width: 120,
          scopedSlots: { customRender: 'failedProcessId' },
          ellipsis: true,
        },
        {
          fixed: 'right',
          title: '不合格操作人',
          
          dataIndex: 'failedOperatorId',
          width: 180,
          scopedSlots: { customRender: 'failedOperatorId' },
          ellipsis: true,
        },
        {
          fixed: 'right',
          title: '操作',
          
          dataIndex: 'actions',
          ellipsis: true,
          scopedSlots: { customRender: 'actions' },
        },
      ],
      filterForm: {
        handleStatus: undefined,
        orderCode: '',
        batchCode: '',
        goodsName: '',
        processName: '',
        operateId: '',
        applyTime: '',
        applyTimeBegin: '',
        applyTimeEnd: '',
      },
      filteredFormLable: {
        handleStatus: '处理状态',
        orderCode: '工单编号',
        batchCode: '批次编号',
        goodsName: '产品名称',
        processName: '工序名称',
        operateId: '操作人',
        applyTime: '提交时间',
        spec:'规格'
      },
      filterUName: '',
      actionRecords: [],
      handelTable: {
        handleList: [] /* 处理列表总数据 */,
        handlePageList: [] /* 处理列表分页数据 */,
        handleSelectedRowKeys: [], // 处理列表已选择key
        handleSelectList: [] /* 处理列表已选择数据 */,
        //全选按钮
        listIndeterminate: false,
        listCheckAll: false,
        /* 分页参数 */
        indeterminate: false,
        checkAll: false,
        current: 1,
        total: 0,
        pageSize: 10,
        loading: false,
        pageSizeOptions: ['10', '20', '30'],
      },
      handleSelectedRows: [], // 暂存主列表已选择项
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
      dateForm: {}, // 列表时间与筛选表单时间v-model同一个值
      allRequistData: [],
      failedList: [],
      failedOperatorList: [],
      tableKey: 1.9,
      modalKey: 1.8,
      loadingBatch: false
    }
  },
  components: {
    SetColumn,
    crumbs,
    BatchProduction,
    windowDetail
  },
  watch: {
    'handelTable.handleList'(nVal) {
      if (nVal.length > 10) {
        this.handelTable.handlePageList = this.handelTable.handleList.slice(0, 10)
      } else {
        this.handelTable.handlePageList = this.handelTable.handleList
      }
    },
  },
  computed: {
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum + 60
    },
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        if (key == 'operateId') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterUName,
            key,
          })
        } else if (key == 'applyTime') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm.applyTimeBegin
              ? moment(this.filterForm.applyTimeBegin).format('YYYY-MM-DD') + '-' + moment(this.filterForm.applyTimeEnd).format('YYYY-MM-DD')
              : '',
            key,
          })
        } else if (key == 'handleStatus' && this.filterForm[key]) {
          list.push({
            title: this.filteredFormLable[key],
            text: this.statusToText(this.filterForm[key]),
            key,
          })
        } else if (key == 'applyTimeBegin' || key == 'applyTimeEnd') {
          // 什么事都不干
        } else {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key,
          })
        }
      }
      return list
    },
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key]) {
          nums += 1
          if (key == 'applyTimeBegin') {
            nums -= 1
          }
        }
      }
      return nums
    },
  },
  created() {
    this.initData()
    this.requestData()
  },
  mounted() {},
  methods: {
    // 批次生产记录弹窗列表
    batchRecord(record) {
      let obj = {
        id: record.batchId,
        orderId: record.orderId,
        batchCode: record.batchCode,
      }
      this.$refs.BatchProduction.showModal(obj, 'BATCH_PRODUCTION_DEFECTS_PENDING_LIST')
    },
    // 查不合格工序下拉
    getFailedList(v, i) {
      this.handelTable.handlePageList.forEach(item => {
        this.failedList.push({
          list: []
        })
      })
      let par = {
        orderId: v.orderId,
        taskId: v.taskId
      }
      API.queryProcessByOrderTaskId(par).then(res => {
        this.failedList[i].list = res.result || []
      })
    },
    changeOperator() {
      this.modalKey += 1
      this.failedProcessIndex += 1
    },
    // 查不合格人下拉
    changeProcess(v, i, r) {
      this.modalKey += 1
      this.failedProcessIndex += 1
      if (!v) {
        return
      }
      this.getFailedList(r, i)
      this.handelTable.handlePageList.forEach(item => {
        this.failedOperatorList.push({
          list: []
        })
      })
      let obj = this.failedList[i].list.find(f => f.failedProcessId == v)
      console.log(obj,'objpbj',this.failedList,v);
      this.handelTable.handlePageList[i].failedTaskId = obj.failedTaskId
      this.handelTable.handlePageList[i].failedOperatorId = this.handelTable.handlePageList[i].operatorId.split(',')
      this.getReportTeam(r,i)
    },
    async getReportTeam(e,i) {
      await API.queryOperatorByFailedProcessId({failedProcessId: e.processId, orderId: e.orderId}).then(res => {
        if (res.result) {
          this.$nextTick(() => {
            this.failedOperatorList[i] = {list: res.result}
          })
          if (i == this.handelTable.handleList.length - 1) {
            setTimeout(() => {
              this.loadingBatch = false
              this.handleVisible = true
              this.$forceUpdate()
            }, 1000);
          }
          console.log('this.failedOperatorList:',this.failedOperatorList);
        }
      })
    },
    changeStatus(v, key) {
      if (v.length == 0) {
        this.filterForm[key] = undefined
      }
    },
    // 处理状态转文字
    statusToText(v) {
      let text = []
      let statusObj = {
        notStart: '未开始',
        handling: '正在处理',
        finish: '处理完成',
      }
      v.forEach(value => {
        text.push(statusObj[value])
      })
      return text.join(',')
    },
    /* 日期选中 */
    onOk(value) {
      if (value.length == 0) {
        this.filterForm.applyTimeBegin = ''
        this.filterForm.applyTimeEnd = ''
        this.dateForm.applyTime = null
        return
      }
      this.filterForm.applyTimeBegin = moment(value[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.filterForm.applyTimeEnd = moment(value[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      console.log('onOk: ', value)
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('看看这是啥33：', sorter)
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: camelCase2UnderLine(sorter.columnKey),
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    // 删除处理列表
    handleDelete(i) {
      for (let j = 0; j < this.handelTable.handleSelectList.length; j++) {
        const han = this.handelTable.handleSelectList[j];
        if (han.id == this.handelTable.handleList[i].id ) {
          this.handelTable.handleSelectList.splice(j, 1)
        }
      }
      for (let k = 0; k < this.handelTable.handleSelectedRowKeys.length; k++) {
        const row = this.handelTable.handleSelectedRowKeys[k];
        if (row == this.handelTable.handleList[i].id) {
          this.handelTable.handleSelectedRowKeys.splice(k, 1)
        }
      }
      this.handelTable.handleList.splice(i, 1)
      this.checkHandleBoxStatus()
      console.log(this.handelTable);
    },
    /* 处理 */
    handleOk() {
      // return
      if (this.handelTable.handleSelectList.length == 0) {
        this.$antdMessage.info('请先选择数据')
        return
      }
      for (let i = 0; i < this.handelTable.handleSelectList.length; i++) {
        const item = this.handelTable.handleSelectList[i]
        if (!item.handleType || !item.num) {
          this.$antdMessage.error('处理方式和处理数量必填')
          return
        }
      }
      let queryData = this.handelTable.handleSelectList.map((item) => {
        item.failedOperatorId = item.failedOperatorId.join(',')
        return item
      })
      console.log(queryData);
      this.confirmHandleLoading = true
      API.messNotQualityHandleIinfoHandle(queryData).then((res) => {
        this.confirmHandleLoading = false
        if (res.code == 200) {
          this.$antdMessage.success(res.message)
          this.handleSearch()
        } else {
          this.$antdMessage.error(res.message)
        }
        this.handleCancel()
      })
    },
    /* 取消处理 */
    handleCancel() {
      this.handelTable.handleSelectedRowKeys = []
      this.handelTable.handleSelectList = []
      this.handelTable.listIndeterminate = false
      this.handelTable.listCheckAll = false
      this.handelTable.indeterminate = false
      this.handelTable.loading = false
      this.handelTable.current = 1
      this.handelTable.pageSize = 10
      this.handleVisible = false
    },
    /* 筛选弹窗中筛选操作人 */
    userFilter(storeVals, row) {
      console.log('row:', row)
      let uIds = []
      let uNames = []
      if (row.length > 0) {
        row.forEach((u) => {
          uIds.push(u.id)
          uNames.push(u.realname)
        })
        this.filterForm.operateId = uIds.join(',')
        this.filterUName = uNames.join(',')
        this.handleSearch()
      } else {
        this.filterForm.operateId = ''
        this.filterUName = ''
      }
    },
    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      // confirm() //用来关闭搜索弹窗
      // clearFilters() //用来重置搜索内容
      // console.log('这都是啥00：', selectedKeys)
      // console.log('这都是啥11：', confirm)
      // console.log('这都是啥22：', dataIndex)
      // console.log('这都是啥33：', clearFilters)
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      if (key == 'handleStatus') {
        this.filterForm[key] = undefined
      } else if (key == 'operateId') {
        this.userIds = ''
        this.filterUName = ''
        this.filterForm[key] = ''
      } else if (key == 'applyTime') {
        this.filterForm.applyTimeBegin = ''
        this.filterForm.applyTimeEnd = ''
        this.dateForm.applyTime = null
        this.filterForm[key] = ''
      } else {
        this.filterForm[key] = ''
      }
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        handleStatus: undefined,
        orderCode: '',
        goodsName: '',
        processName: '',
        operateId: '',
        applyTime: '',
        applyTimeBegin: '',
        applyTimeEnd: '',
        spec:'',
      }
      this.userIds = ''
      this.filterUName = ''
      this.showFilter = false
      this.dateForm = {}
      this.handleSearch()
    },
    /* 初始/加载设置列 */
    initData() {
      var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.DEFECTS_PENDING_LIST)
      this.columns = getNewColumns(columnsValue, JSON.parse(oldValue), actionArr, this.columns)
    },
    /* 请求列表数据 */
    requestData(check) {
      let obj = {}
      for (let key in this.filterForm) {
        if (this.filterForm[key]) {
          if (key == 'handleStatus' && this.filterForm[key]) {
            obj[key] = this.filterForm[key].join(',')
          } else {
            obj[key] = this.filterForm[key]
          }
        }
      }
      console.log(this.filterForm, obj)
      let parameter = {
        pageNo: this.current,
        pageSize: this.pageSize,
        ...obj,
        ...this.sortForm,
      }
      API.messNotQualityHandleIinfo(parameter).then((res) => {
        if (res.code == 200) {
          if (res.result.total) {
            this.total = res.result.total
          } else {
            this.total = 0
          }
          this.modelList = res.result.records
          // this.modelList.forEach(item => {
          //   item.notQualityNum = numFormat(item.notQualityNum)
          //   item.alreadyHandleNum = numFormat(item.alreadyHandleNum)
          // })
          this.allRequistData = this.allRequistData.concat(res.result.records)
          if (check) {
            this.checkBoxStatus()
          }
        }
      })
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData( columnsValue, this.BUSI_CONST.Entity.DEFECTS_PENDING_LIST, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      this.columns = getNewColumns(columnsValue, emitArr, actionArr)
      console.log(this.columns)
      localStorage.setItem(this.BUSI_CONST.Entity.DEFECTS_PENDING_LIST, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    /* 导出 */
    exportFile() {},
    /* 编辑 */
    handleEdit(v) {
      this.$router.push({
        path: '/qualityManagement/defectsDealDetail',
        query: { id: v.id },
      })
    },
    /* 工单详情 */
    orderDetail(v) {
      this.$refs.windowDetail.initDetail({id: v.orderId})
    },
    /* 处理 */
    handle(v) {
      this.failedList = []
      this.failedOperatorList = []
      this.handelTable.handleList = [JSON.parse(JSON.stringify(v))]
      this.handelTable.handleList.map((e) => {
        e.failedProcessId = e.processId
        e.failedTaskId = e.processId
        let names = e.operatorIdText.split(',')
        let ids = e.operatorId.split(',')
        let arr = []
        ids.forEach((id, i) => {
          arr.push({
            failedOperatorId: id,
            failedOperatorName: names[i]
          })
        })
        this.failedList.push({
          list: [{
            failedProcessName: e.processName,
            failedProcessId: e.processId
          }]
        })
        e.failedOperatorId = ids
        API.queryOperatorByFailedProcessId({failedProcessId: e.processId, orderId: e.orderId}).then(res => {
          if (res.result) {
            this.failedOperatorList = [{
              list: res.result
            }]
          }
          this.handleVisible = true
        })
        return e
      })
      // this.handelTable.handleSelectList = [v]
      
      console.log(v)
    },
    //点击返回按钮
    goBack() {
      console.log('goback')
    },
    /* 列表选择 */
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log('selectedRowKeys changed: ', selectedRows)
      this.selectedRowKeys = selectedRowKeys
      this.handelTable.handleList = selectedRows
      this.handleSelectedRows = selectedRows
      this.checkBoxStatus()
    },
    /* 处理列表选择 */
    handleSelectChange(selectedRowKeys, selectedRows) {
      console.log('selectedRowKeys changed: ', selectedRows)
      this.handelTable.handleSelectedRowKeys = selectedRowKeys
      this.checkHandleBoxStatus()
      this.handelTable.handleSelectList = selectedRows
    },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.handelTable.handleList = this.handelTable.handleList.filter((each) => {
            return each.id != item.id
          })
          this.handelTable.handleList.push(item)
        }
        this.handleSelectedRows = this.handelTable.handleList
      } else {
        this.handleSelectedRows = []
        this.handelTable.handleList = []
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.modelList) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 批量处理
    batchAction() {
      console.log('this.selectedRowKeys', this.allRequistData)
      this.failedList = []
      this.failedOperatorList = []
      var obj = {};
      let allarr = JSON.parse(JSON.stringify(this.allRequistData))
      const arrays = allarr.reduce((setArr, item) => {
        obj[item['id']] ? '' : obj[item['id']] = true && setArr.push(item);
        return setArr;
      }, []);
      console.log(arrays)
      // return
      for (let i = 0; i < this.handleSelectedRows.length; i++) {
        const ele = this.handleSelectedRows[i]
        if (ele.handleStatus == 'finish') {
          this.$antdConfirm({
            title: '无法批量处理',
            content: '所选处理单有状态“已完成”的，不能进行处理！',
            onOk() {
              return
            },
            onCancel() {},
          })
          return
        }
      }
      this.handelTable.handleList = []
      for (let i = 0; i < arrays.length; i++) {
        const item = arrays[i];
        for (let j = 0; j < this.selectedRowKeys.length; j++) {
          const ele = this.selectedRowKeys[j];
          if (item.id == ele) {
            this.handelTable.handleList.push(item)
          }
        }
      }
      // this.handelTable.loading = true
      this.handelTable.handleList.forEach((e, i) => {
        e.failedProcessId = JSON.parse(JSON.stringify(e.processId))
        e.failedTaskId = JSON.parse(JSON.stringify(e.processId))
        this.failedList.push({
          list: [{
            failedProcessName: e.processName,
            failedProcessId: e.processId
          }]
        })
        e.failedOperatorId = JSON.parse(JSON.stringify(e.operatorId)).split(',')
        this.getReportTeam(e,i)
        // this.handelTable.handleList[i] = e
      })
      // this.handelTable.handleList = this.handleSelectedRows
      let that = this
      if (that.selectedRowKeys.length > 0) {
        this.loadingBatch = true
        // this.handleVisible = true
      } else {
        that.$antdMessage.info('请先选择数据')
      }
    },
    /* 清除 */
    clearArr() {
      this.selectedRowKeys = []
      this.checkBoxStatus()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    onShowSizeChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    // 处理分页
    handleChangePage(current, pageSize) {
      this.handelTable.current = current
      this.handelTable.pageSize = pageSize
      let cur = 0
      let siz = pageSize * current
      if (current == 1) {
        cur = 0
      } else {
        cur = (current -1) * pageSize
      }
      console.log(this.handelTable.handleList, 'this.handelTable.handleList', cur, siz)
      this.handelTable.loading = true
      setTimeout(() => {
        this.handelTable.handlePageList = this.handelTable.handleList.slice(cur, siz)
        console.log(cur, siz)
        this.handelTable.loading = false
      }, 300)
    },
    handleShowSizeChange(current, pageSize) {
      this.handleChangePage(current, pageSize)
    },
    // 处理全选
    handleCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.handelTable.handleList) {
          this.handelTable.handleSelectedRowKeys = this.handelTable.handleSelectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
          this.handelTable.handleSelectedRowKeys.push(item.id)
          this.handelTable.handleSelectList.push(item)
        }
      } else {
        this.handelTable.handleSelectedRowKeys = []
        this.handelTable.handleSelectList = []
      }
      this.checkHandleBoxStatus()
    },
    checkHandleBoxStatus() {
      if (this.handelTable.handleSelectedRowKeys.length == 0) {
        this.handelTable.listIndeterminate = false
        this.handelTable.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.handelTable.handleList) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.handelTable.handleSelectedRowKeys)
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.handelTable.listIndeterminate = false
          this.handelTable.listCheckAll = true
        } else {
          this.handelTable.listIndeterminate = true
          this.handelTable.listCheckAll = false
        }
      }
    },
    // 删除全部
    deleteAll() {
      // this.handelTable.handleList = []
      if (this.handelTable.handleSelectList.length == 0) {
        this.$antdMessage.info('请先选择数据')
        return
      }
      for (let i = 0; i < this.handelTable.handleSelectList.length; i++) {
        const item = this.handelTable.handleSelectList[i]
        for (let j = 0; j < this.handelTable.handleList.length; j++) {
          const ele = this.handelTable.handleList[j];
          if (item.id == ele.id) {
            this.handelTable.handleList.splice(j, 1)
          }
        }
      }
    },
    inputNum(e, i) {
      let nums = clearNoNum(this.handelTable.handleList[i].num)
      let canNums = Number(this.handelTable.handleList[i].canHandleNum)
      nums
      if (Number(nums) > canNums) {
        this.handelTable.handleList[i].num = ''
        this.$antdMessage.error(`处理数量不能大于可处理数量${canNums}`)
        return
      }
      this.handelTable.handleList[i].num = nums
    },
    blurNum(e, i) {
      if (e.target.value == '0') {
        this.handelTable.handleList[i].num = ''
        this.$antdMessage.error(`处理数量必须大于0`)
      }
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.header {
  width: 150%;
  margin: -12px -12px @distance4;
}
.backBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .backC {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
.j-table-force-nowrap {
  margin-top: @distance1;
}
.btns {
  margin-left: @distance5;
}
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
}
.mg-left {
  margin-left: @distance3;
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}
.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
/deep/ .ant-card-body {
  height: calc(100vh - 214px);
  overflow: hidden;
  padding: 20px 16px;
}
.notStart {
  color: @warFont;
}
.handling {
  color: @normalFont;
}
.finish {
  color: @passFont;
}
</style>
